<template>
  <div class="mapBox">
    <div id="gis-dialog"></div>
    <div class="header">
      <topCom />
    </div>
    <div class="aside">
      <tabIndex />
    </div>
    <div class="footer">
      <footCom />
    </div>
    <div class="toolbar">
      <!-- {{ store.layerData.join(",") }} -->
      <toolbar />
    </div>
    <div class="comview">
      <roomDialog
        v-for="(item, index) in store.componentsData"
        :key="item.id"
        :title="item.title"
        :isFixed="true"
        :isuseDraggable="true"
        @close="closeCom(item.id)"
        :yheight="getHeight(item.type, index)"
        :size="getComponent(item.type)"
      >
        <template v-if="item.type === 'text'">
          <textDialog />
        </template>
        <template v-else-if="item.type === 'chart'">
          <chartDialog :mimedata="item.data" />
        </template>
        <template v-else>
          <tableDialog :mimedata="item.data" />
        </template>
      </roomDialog>
    </div>
    <div id="map" ref="mapElement"></div>
  </div>
  <div ref="popup" class="ol-popup">
    <div class="namecenter" v-show="searchpoitype == 2">{{ searchpoiName }}</div>
    <autoDialog
      :isuseDraggable="false"
      size="small"
      :title="searchpoiName"
      :isFixed="false"
      @close="closePopup"
      v-show="searchpoitype == 1"
    >
      <!-- <roomDialog @close="closePopup" :title="searchpoiName" :isuseDraggable="false" size="small"> -->
      <a href="#" id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-content" class="scroll-b"> </div>
    </autoDialog>
  </div>
</template> 
  <script setup>
import { initMap } from '../api/gis2d/mapbase'
import topCom from '../layer/header.vue'
import tabIndex from './components/tabIndex.vue'
import footCom from './components/footer.vue'
import toolbar from './components/toolbar.vue'
import roomDialog from '../components/roomDialog.vue'
import textDialog from './components/other/textDialog.vue'
import chartDialog from './components/other/chartDialog.vue'
import tableDialog from './components/other/tableDialog.vue'
import { onMounted, ref, reactive, watch, provide, onUnmounted } from 'vue'
import { createPoint, addMapLayer, delMapLayer, init4490, clearFlag,loadInitView } from '../api/gis2d/maputils'
import { useRoute, useRouter } from 'vue-router'
import { useMapStoreStore } from '../stores/index'
import {
  createFlashingPoint,
  createEarthquakeRadiusLayer,
  updateEarthquakeRadius,
  addHeatMap,
  mapFlag,
  mapLayers,
  createPointImg
} from '../api/gis2d/maputils'
import Overlay from 'ol/Overlay'
import { transform } from 'ol/proj'
import dayjs from 'dayjs'

const route = useRoute()
const store = useMapStoreStore()
const data = JSON.parse(route.query.data)
store.eqid = data.id

store.earthquakeInfo = data

let yheight = 0
let oldt = ''
const getComponent = (type) => {
  if (type === 'text') {
    return 'small'
  }
  return 'big'
}
const getHeight = (type, i) => {
  if (i === 0) {
    oldt = type
    return 0
  }
  yheight += oldt == 'text' ? 210 : 300
  oldt = type
  return yheight
}
const closeCom = (i) => {
  store.hideComponents(i)
}
watch(
  () => store.componentsData,
  () => {
    yheight = 0
    oldt = ''
  }
)

const closeFlag = ref(true)
const popup = ref(null)
var popups
const searchpoiName = ref('')
const searchpoitype = ref(1)
const closePopup = () => {
  popups.setPosition(undefined)
  closeFlag.value = false
}
const mapElement = ref(null)
let map = null

const createPoiSearchDom = (data) => {
  var positions = data.lonlat.split(',')
  searchpoitype.value = 1
  searchpoiName.value = data.name
  let html = `
    <div class='search-poi' style='  height: 100%; line-height: 30px;font-size:18px'>
      <div>地址:&nbsp;${data.address}</div>
      <div>名称:&nbsp;${data.name}</div>
       <div>震中距:&nbsp;${data.distance}公里</div>
      <div>经度:&nbsp;${positions[0]}</div>
       <div>纬度:&nbsp;${positions[1]}</div>
    </div>
  `
  document.getElementById('popup-content').innerHTML = html
}
const createHistoryhDom = (d) => {
  searchpoitype.value = 1
  var data = d.features[0].properties
  searchpoiName.value = data.macroscopic + data.shockLevel + '级地震'
  var date = dayjs(data.year + data.month + data.day + data.h + ':' + data.m).format(
    'YYYY-MM-DD HH:mm'
  )
  if (data.die > 0 || data.economics > 0 || data.injured > 0) {
    let html = `
    <div class='search-poi' style='  height: 100%; line-height: 30px;font-size:18px'>
      <div>地震日期:&nbsp;${date}</div>
       <div>位置:&nbsp;${data.macroscopic}</div>
       <div>震级:&nbsp;${data.shockLevel}级</div>
        <div>死亡:&nbsp;${Number(data.die)}人</div>
           <div>受伤:&nbsp;${Number(data.injured)}人</div>
                <div>经济损失:&nbsp;${Number(data.economics)}万元</div>
           <div>经度:&nbsp;${data.longitude}</div>
       <div>纬度:&nbsp;${data.dimensionality}</div>
    </div>
  `
    document.getElementById('popup-content').innerHTML = html
    return
  }
  let html = `
    <div class='search-poi' style='  height: 100%; line-height: 30px;font-size:18px'>
      <div>地震日期:&nbsp;${date}</div>
      <div>位置:&nbsp;${data.macroscopic}</div>
       <div>震级:&nbsp;${data.shockLevel}级</div>
           <div>经度:&nbsp;${data.longitude}</div>
       <div>纬度:&nbsp;${data.dimensionality}</div>
    </div>
  `
  document.getElementById('popup-content').innerHTML = html
}
const createZhyyAndZkyy = (d,t) => {
  searchpoitype.value = 2
  var data = d.features[0].properties
  console.log(data);
  
  searchpoiName.value = data[t+""] || data.name
  let html = `
    <div class='search-poi' style='  height: 100%; line-height: 30px;font-size:18px'>
      <div>地址:&nbsp;${data.address}</div>
      <div>名称:&nbsp;${data.name}</div>
    </div>
  `
  document.getElementById('popup-content').innerHTML = html
}

watch(()=>store.layerData,(e)=>{
  closePopup()
})

const initOverlayAndSingleclick = () => {
  // 创建popup
  popups = new Overlay({
    element: popup.value,
    autoPan: true,
    positioning: 'bottom-center',
    stopEvent: true,
    autoPanAnimation: {
      duration: 250
    }
  })
  map.on('singleclick', function (e) {
    if (
      mapFlag['lsdz'] ||
      mapFlag['lsczdz'] ||
      mapFlag['zkyy'] ||
      mapFlag['zhyy'] ||
      mapFlag['yey'] ||
      mapFlag['xx'] ||
      mapFlag['zx'] ||
      mapFlag['gdyx'] ||
      mapFlag['lshpfb']
    ) {
      var viewResolution = map.getView().getResolution()
      var url = getFeatureUrl('lsdz', e.coordinate, viewResolution)
      var surl = getFeatureUrl('lsczdz', e.coordinate, viewResolution)
      var zhyyurl = getFeatureUrl('zhyy', e.coordinate, viewResolution)
      var zkyyurl = getFeatureUrl('zkyy', e.coordinate, viewResolution)

      var yeyurl = getFeatureUrl('yey', e.coordinate, viewResolution)
      var xxurl = getFeatureUrl('xx', e.coordinate, viewResolution)
      var zxurl = getFeatureUrl('zx', e.coordinate, viewResolution)
      var gdyxurl = getFeatureUrl('gdyx', e.coordinate, viewResolution)
      var hpurl = getFeatureUrl('lshpfb', e.coordinate, viewResolution,"0.2,0.1,0.0")
      getFeatureData(url, e.coordinate, 'lsdz')
      getFeatureData(surl, e.coordinate, 'lsczdz')
      getFeatureData(zhyyurl, e.coordinate, 1)
      getFeatureData(zkyyurl, e.coordinate, 1)

      getFeatureData(yeyurl, e.coordinate, 1)
      getFeatureData(xxurl, e.coordinate, 1)
      getFeatureData(zxurl, e.coordinate, 1)
      getFeatureData(gdyxurl, e.coordinate, 1)
       getFeatureData(hpurl, e.coordinate, 1)
    }
    closePopup()
    var pixel = map.getEventPixel(e.originalEvent)
    map.forEachFeatureAtPixel(pixel, function (feature) {
      if (feature.get('type') === 'search-poi') {
        const data = feature.get('data')
        closeFlag.value = true
        var coodinate = e.coordinate
        popups.setPosition(coodinate)
        map.addOverlay(popups)
        createPoiSearchDom(data)
      }
    })
  })
}

function getFeatureUrl(layercode, coordinate, viewResolution,filter) {
  var url =
    mapFlag[layercode] &&
    mapLayers[layercode].getSource().getFeatureInfoUrl(coordinate, viewResolution, 'EPSG:3857', {
      INFO_FORMAT: 'application/geojson',
      QUERY_LAYERS: filter || '0.0,0.1'
    })

  return url
}

function getFeatureData(url, coordinate, type) {
  if (!url) return
  fetch(url)
    .then(function (response) {
      if (response.ok) {
        return response.json() // 解析JSON数据
      }
      throw new Error('Network response was not ok.')
    })
    .then(function (data) {
      map.addOverlay(popups)
      // 在点击位置显示弹出框
      popups.setPosition(coordinate)
      console.log(coordinate)
      if (type == 1) {
        createZhyyAndZkyy(data,'disaster_location')
        return
      }

      createHistoryhDom(data)
    })
    .catch(function (error) {
      // console.error('Error:', error)
    })
}

watch(
  () => store.radius,
  (newval) => {
    updateEarthquakeRadius(newval, [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude])
  }
)

let intervalId = null
const initEarthQuakeCenter = () => {
  const earthquakeCenterLonLat = [store.earthquakeInfo.longitude, store.earthquakeInfo.latitude]
  createPointImg(earthquakeCenterLonLat, '/static/assets/3d/zz.png')
  loadInitView(store.eqid,store.earthquakeInfo.version)
  createEarthquakeRadiusLayer(store.radius, earthquakeCenterLonLat)
  store.updateComponentsData([
    {
      id: 1011,
      title: '震区基本情况',
      type: 'text',
      data: 'zxz'
    }
  ])
}

onMounted(() => {
  map = initMap({ map: mapElement.value })
  init4490()

  initEarthQuakeCenter()
  initOverlayAndSingleclick()
  // addHeatMap()
})
onUnmounted(() => {
  store.initStore()
  clearFlag();
  map.setTarget(null);
  map = null
})
</script>

  <style lang="scss">
.scroll-b {
  &::-webkit-scrollbar {
    width: 6px;
    height: 8px;
  }
  &::-webkit-scrollbar-button {
    display: none;
  }
  &::-webkit-scrollbar-thumb {
    background: #01c2ff;
    cursor: pointer;
    border-radius: 4px;
  }
  &::-webkit-scrollbar-corner {
    display: none;
  }
  &::-webkit-resizer {
    display: none;
  }
}
</style>
  <style lang="scss" scoped>
.namecenter {
  padding: 2px 15px;
  height: 40px;
  font-size: 22px;
  font-weight: bold;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 10, 0.8);
  box-sizing: border-box;
  border: 1px solid #0e9cff;
  box-shadow: inset 0px 0px 87px 0px rgba(1, 194, 255, 0.4);
  color: #ffffff;
}
.mapBox {
  position: relative;
}
#map,
.mapBox {
  width: 100vw;
  height: 100vh;
}
#map {
  position: absolute;
  top: 0;
  left: 0;
}
.header {
  position: absolute;
  top: 0;
  width: 100%;
  height: 9.2592vh;
  z-index: 1;
}
.aside {
  position: absolute;
  top: 9.2592vh;
  left: 0px;
  height: calc(100% - 9.2592vh);
  width: 300px;
  z-index: 2;
}
.footer {
  position: absolute;
  bottom: 0;
  left: 80px;
  width: calc(100% - 80px);
  height: 60px;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0px -4px 10px 0px rgba(0, 65, 133, 0.3);
  z-index: 1;
}
.toolbar {
  position: absolute;
  right: 20px;
  top: 8vh;
  height: 100px;
  z-index: 11;
}
.comview {
  position: absolute;
  right: 20px;
  top: calc(8vh + 100px);
  /* height: 76vh; */
  /* display: flex;
  flex-direction: column;
  justify-content: space-around; */
  /* flex-wrap: wrap; */
}
.ol-popup {
  z-index: 99;
  margin-bottom: 15px;
  #popup-content {
    height: 100%;
    overflow: auto;
    .search-poi {
      line-height: 30px;
    }
  }
}
</style>
  
  